import { useUserStore } from "@/stores/modules/user";
import qs from "qs";
// import { ElMessageBox } from "element-plus";

export default class WebSocketClient {
  private url: string;
  private ws: WebSocket | null = null;
  private messageHandler: ((message: string) => void) | null = null;
  private heartbeatInterval = 30000; //心跳间隔
  private heartbeatTimer: NodeJS.Timeout | null = null;
  private connectTimes = 1; // 重连次数
  private maxConnectTimes = 3; // 最大重连次数
  private reconnectInterval = 3000; //重连间隔时间
  private reconnectTimer: NodeJS.Timeout | null = null;
  private connectionStatus = false;
  private isActiveClose = false; //是否是主动关闭
  private path = ""; //连接通道

  /**
   * @param path 连接通道
   * @param params 参数
   */
  constructor(path: string = "", params: object = {}) {
    const userStore = useUserStore();
    this.path = path;
    let token = "";
    let baseUrl = "";
    if (path.includes("chatAir_doctor")) {
      token = userStore.userInfo?.callToken || "";
      baseUrl = import.meta.env.VITE_WS_URL_RTC;
    } else {
      token = userStore.userInfo?.dataToken || "";
      baseUrl = import.meta.env.VITE_WS_URL_DATA;
    }
    this.url = `${baseUrl}${path}?authorization=${token}&${qs.stringify(params)}`;
    this.connect();
    this.setupNetworkStatusListener();
  }
  public setMessageHandler(handler: (message: string) => void) {
    this.messageHandler = handler;
  }
  public sendMessage(message: string) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(message);
    } else {
      console.error("WebSocket is not open.");
    }
  }
  public close() {
    this.isActiveClose = true;
    this.stopHeartbeat();
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
    }
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }
  private connect() {
    this.ws = new WebSocket(this.url);
    this.ws.onopen = () => {
      console.log("%cWebSocket已连接！", "color: #43bb88;font-size: 24px;font-weight: bold;text-decoration: underline;");
      this.startHeartbeat();
      this.connectTimes = 0;
    };
    this.ws.onmessage = event => {
      // let data = JSON.parse(event.data);
      // if (data.code === 200 || data.reply === "pong") {
      //   this.connectionStatus = true;
      //   return;
      // }
      // if (this.messageHandler) {
      //   this.messageHandler(data);
      // }
      if (
        event.data == "ok" ||
        event.data == "pong" ||
        JSON.parse(event.data).code == 200 ||
        JSON.parse(event.data).reply == "pong"
      ) {
        this.connectionStatus = true;
        return;
      }
      if (this.messageHandler) {
        this.messageHandler(JSON.parse(event.data));
      }
    };
    this.ws.onerror = () => {
      console.log(
        `%cWebSocket连接失败，正尝试第${this.connectTimes}次连接`,
        "color: #72ce50;font-size: 22px;font-weight: bold;text-decoration: underline;"
      );
      // this.reconnect();
      this.ws?.close();
    };
    this.ws.onclose = () => {
      if (this.isActiveClose || this.connectTimes > this.maxConnectTimes) {
        console.log(
          `%c通道%c${this.path}%c已关闭!`,
          "color: #ce4a08;font-size: 24px",
          "color: #ce4a08;font-size: 24px;font-weight: bold;",
          "color: #ce4a08;font-size: 24px;"
        );
        if (!this.isActiveClose) {
          // ElMessageBox.confirm("WebSocket连接失败，请检查网络后重连", "Warning", {
          //   confirmButtonText: "重连",
          //   cancelButtonText: "刷新",
          //   type: "warning",
          //   draggable: true,
          //   closeOnClickModal: false,
          //   showClose: false
          // })
          //   .then(() => {
          //     this.connectTimes = 0;
          //     this.reconnect();
          //   })
          //   .catch(() => {
          //     window.location.reload();
          //   });
        }
      } else {
        console.log(
          `%cWebSocket连接已关闭!，正尝试第${this.connectTimes}次连接`,
          "color: #ce4a08;font-size: 22px;font-weight: bold;text-decoration: underline;"
        );
        this.reconnect();
      }
    };
  }
  //开始心跳检测
  private startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN && this.connectionStatus) {
        this.ws.send(JSON.stringify({ msgType: 1101 }));
        this.connectionStatus = false;
      } else {
        this.reconnect();
      }
    }, this.heartbeatInterval);
  }
  //停止心跳检测
  private stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }
  //重连
  private reconnect() {
    this.stopHeartbeat();
    this.ws?.close();
    this.ws = null;
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
    }
    this.connectTimes += 1;
    this.reconnectTimer = setTimeout(() => {
      this.connect();
    }, this.reconnectInterval);
  }

  //监听网络变化
  private setupNetworkStatusListener() {
    window.addEventListener("online", () => {
      console.log("Online");
      if (!this.ws || this.ws.readyState === WebSocket.CLOSED) {
        this.connect();
      }
    });

    window.addEventListener("offline", () => {
      console.log("Offline");
      if (this.ws && this.ws.readyState !== WebSocket.CLOSED) {
        this.ws.close();
      }
    });
  }
}
